<template>
  <div>
    <headers title="登录"></headers>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { pattern: pattern1, required: true, message: '请输入手机号' },
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            { pattern: pattern2, required: true, message: '请填写密码' },
          ]"
        />
        <van-field
          v-model="sms"
          label="短信验证码"
          placeholder="获取验证码"
          :rules="[
            {  required: true, message: '请点击获取验证码' },
          ]"
        >
    <template #button>
          <van-button round block size="small" type="primary" v-if="item==0" @click="onoute" >
          发送验证码
        </van-button>
          <van-button round block type="primary" v-else @click="onoute">
          {{ item }}s倒计时
        </van-button>
    </template>
    
    
    </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div style="width: 100%; text-align: right">
      <router-link to="reg">立即注册?</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { loginApi } from "@/api/api";
import headers from "@/components/header.vue";
import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";

const router = useRouter();
const route = useRoute();

const pattern1=/^1[3-9]\d{9}$/
const pattern2=/^\d{6}$/

const username = ref("");
const password = ref("");
const onSubmit = (values) => {
  console.log("submit", values);
 loginApi(username.value, password.value).then((res) => {
    if (res.data.code == 0) {
      showToast("登录成功");
      localStorage.setItem('token',res.data.data.token);
      localStorage.setItem('username',res.data.data.username);

      router.push('/home/my');
    } else {
      showToast(res.data.msg);
    }
  });
};
const sms=ref([])
const item=ref(0)

const onoute=()=>{
 sms.value=Math.random().toString().slice(2,8);
 item.value=10;
 let time=setInterval(() => {
    item.value--;
    if(item.value==0){
        clearInterval(time)
    }
 }, 1000);
}
</script>

<style lang="scss" scoped></style>
